package leetcode.part1;

import org.junit.Test;

/**
 * 接雨水
 */
public class S42 {
    public int trap(int[] height) {

        int n = height.length;
        int[] leftMax = new int[n];
        leftMax[0] = height[0];
        for (int i = 1; i < n; i++) {
            leftMax[i] = Math.max(leftMax[i - 1], height[i]);
        }
        int[] rightMax = new int[n];
        rightMax[n - 1] = height[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            rightMax[i] = Math.max(rightMax[i + 1], height[i]);
        }

        int result = 0;
        for (int i = 0; i < n; i++) {
            // 选择最小的来减去height，就可以得到雨水高度
            result += Math.min(leftMax[i], rightMax[i] )-height[i];
        }
        return result;
    }

    private int trap2(int[] height) {
        int n = height.length;
        int[] leftDp = new int[n];
        int[] rightDp = new int[n];
        leftDp[0] = height[0];
        rightDp[n - 1] = height[n - 1];
        for (int i = 1; i < n; i++) {
            leftDp[i] = Math.max(leftDp[i - 1], height[i]);
        }
        for (int i = n - 2; i >= 0; i--) {
            rightDp[i] = Math.max(rightDp[i + 1], height[i]);
        }
        int rec = 0;
        for (int i = 0; i < leftDp.length; i++) {
            rec += Math.min(leftDp[i], rightDp[i]) - height[i];
        }
        return rec;
    }


    @Test
    public void test() {
        int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        System.out.println(trap(height));
        System.out.println(trap2(height));
    }
}
